<template>
  <div class="admin-orders-container">
    <el-card>
      <template #header>
        <h2>预定申请订单</h2>
      </template>

      <el-form :inline="true" :model="queryParams">
        <el-form-item label="审批状态">
          <el-select v-model="queryParams.status" placeholder="选择状态" clearable @change="handleQuery" style="width: 100px;">
            <el-option label="待审核" :value="0" />
            <el-option label="已批准" :value="1" />
            <el-option label="未批准" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="orderList" v-loading="loading" style="width: 100%">
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="order-expand-content">
              <p><strong>收货人:</strong> {{ row.consignee }}</p>
              <p><strong>联系电话:</strong> {{ row.phone }}</p>
              <p><strong>收货地址:</strong> {{ row.address }}</p>
              <p><strong>用户备注:</strong> {{ row.remark || '无' }}</p>
              <p v-if="row.rejectionReason"><strong>拒绝理由:</strong> {{ row.rejectionReason }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="animalInfo.name" label="预定宠物" />
        <el-table-column prop="buyerInfo.userAccount" label="申请用户" />
        <el-table-column prop="createTime" label="申请时间">
          <template #default="{ row }">{{ new Date(row.createTime).toLocaleString() }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="statusMap[row.status]?.type || 'info'">{{ statusMap[row.status]?.text }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button v-if="row.status === 0" type="success" size="small" @click="handleApprove(row)" :loading="row.approving">
              批准
            </el-button>
            <el-button v-if="row.status === 0" type="danger" size="small" @click="handleReject(row)" :loading="row.rejecting">
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="total > 0">
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="queryParams.pageSize" :current-page="queryParams.current" @current-change="handlePageChange"/>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// START: 1. 导入新的API函数
import { listAdminOrdersByPageApi, approveOrderApi, rejectOrderApi } from '@/api/order.js';
// END: 1. 导入新的API函数

const loading = ref(true);
const orderList = ref([]);
const total = ref(0);

const queryParams = reactive({ current: 1, pageSize: 10, status: null });
const statusMap = { 0: { text: '待审核', type: 'warning' }, 1: { text: '已通过', type: 'success' }, 2: { text: '未通过', type: 'info' } };

const fetchAdminOrders = async () => {
  loading.value = true;
  try {
    const res = await listAdminOrdersByPageApi(queryParams);
    if (res) {
      // START: 2. 初始化加载状态，增加 rejecting 属性
      orderList.value = res.records.map(item => ({...item, approving: false, rejecting: false}));
      // END: 2. 初始化加载状态
      total.value = Number(res.total);
    } else {
      ElMessage.error(res.message || '获取申请列表失败');
    }
  } catch (error) {
    ElMessage.error('网络请求失败');
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.current = 1;
  fetchAdminOrders();
}

const handlePageChange = (page) => {
  queryParams.current = page;
  fetchAdminOrders();
};

const handleApprove = (row) => {
  ElMessageBox.confirm(`确定批准用户【${row.buyerInfo.userAccount}】对宠物【${row.animalInfo.name}】的预定申请吗？`, '确认批准', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    row.approving = true;
    try {
      const res = await approveOrderApi(row.id);
      if (res) {
        ElMessage.success('批准成功！');
        fetchAdminOrders();
      } else {
        ElMessage.error(res.message || '批准失败');
      }
    } catch (error) {
      const errorMessage = error.response?.data?.message || '操作失败';
      ElMessage.error(errorMessage);
    } finally {
      row.approving = false;
    }
  }).catch(() => {});
};

// START: 3. 添加 handleReject 函数
const handleReject = (row) => {
  ElMessageBox.prompt('请输入拒绝该申请的理由', '确认拒绝', {
    confirmButtonText: '确定拒绝',
    cancelButtonText: '取消',
    inputValidator: (val) => val && val.trim().length > 0, // 确保理由不为空
    inputErrorMessage: '拒绝理由不能为空',
  }).then(async ({ value }) => { // value 就是用户输入的理由
    row.rejecting = true;
    try {
      const res = await rejectOrderApi({ id: row.id, reason: value });
      if (res) {
        ElMessage.success('已拒绝该申请');
        fetchAdminOrders(); // 刷新列表
      } else {
        ElMessage.error(res.message || '操作失败');
      }
    } catch (error) {
      const errorMessage = error.response?.data?.message || '操作失败';
      ElMessage.error(errorMessage);
    } finally {
      row.rejecting = false;
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};
// END: 3. 添加 handleReject 函数

onMounted(fetchAdminOrders);
</script>

<style scoped>
.admin-orders-container { padding: 20px; width: 800px}
.order-expand-content { padding: 10px 20px; background-color: #f9f9f9; }
.pagination-container { display: flex; justify-content: center; margin-top: 20px; }
</style>